/*global Qiniu */
/*global plupload */
/*global FileProgress */
/*global hljs */


$(Wind.use("plupload", function() {
    var uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'pickfiles',
        container: 'container',
        drop_element: 'container',
        max_file_size: '1000mb',
        flash_swf_url: '/public/plupload/js/Moxie.swf',
        dragdrop: true,
        chunk_size: '4mb',
        multi_selection: !(mOxie.Env.OS.toLowerCase()==="ios"),
        uptoken_url: $('#uptoken_url').val(),
        uptoken_func: function(){
            var ajax = new XMLHttpRequest();
            ajax.open('GET', $('#uptoken_url').val(), false);
            ajax.setRequestHeader("If-Modified-Since", "0");
            ajax.send();
            if (ajax.status === 200) {
                var res = JSON.parse(ajax.responseText);
                console.log('custom uptoken_func:' + res.uptoken);
                return res.uptoken;
            } else {
                console.log('custom uptoken_func err');
                return '';
            }
        },
        domain: 'http://7xr6vu.com1.z0.glb.clouddn.com/',
        get_new_uptoken: false,
        // downtoken_url: '/downtoken',
        unique_names: true,
        // save_key: true,
        // x_vars: {
        //     'id': '1234',
        //     'time': function(up, file) {
        //         var time = (new Date()).getTime();
        //         // do something with 'time'
        //         return time;
        //     },
        // },
        auto_start: true,
        log_level: 1,
        init: {
            'FilesAdded': function(up, files) {
                $('table').show();
                $('#success').hide();
                plupload.each(files, function(file) {
                    var progress = new FileProgress(file, 'fsUploadProgress');
                    progress.setStatus("等待...");
                    progress.bindUploadCancel(up);
                });
            },
            'BeforeUpload': function(up, file) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                if (up.runtime === 'html5' && chunk_size) {
                    progress.setChunkProgess(chunk_size);
                }
            },
            'UploadProgress': function(up, file) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                progress.setProgress(file.percent + "%", file.speed, chunk_size);
            },
            'UploadComplete': function() {
                $('#success').show();
            },
            'FileUploaded': function(up, file, info) {
                var progress = new FileProgress(file, 'fsUploadProgress');
                progress.setComplete(up, info);
            },
            'Error': function(up, err, errTip) {
                $('table').show();
                var progress = new FileProgress(err.file, 'fsUploadProgress');
                progress.setError();
                progress.setStatus(errTip);
            },
            'Key': function(up, file) {
                // 为文件名添加前缀video
                return 'video/' + file.name;
            }
        }
    });

    uploader.bind('FileUploaded', function() {
        console.log('hello man,a file is uploaded');
    });
    $('#container').on(
        'dragenter',
        function(e) {
            e.preventDefault();
            $('#container').addClass('draging');
            e.stopPropagation();
        }
    ).on('drop', function(e) {
        e.preventDefault();
        $('#container').removeClass('draging');
        e.stopPropagation();
    }).on('dragleave', function(e) {
        e.preventDefault();
        $('#container').removeClass('draging');
        e.stopPropagation();
    }).on('dragover', function(e) {
        e.preventDefault();
        $('#container').addClass('draging');
        e.stopPropagation();
    });



    $('#show_code').on('click', function() {
        $('#myModal-code').modal();
        $('pre code').each(function(i, e) {
            hljs.highlightBlock(e);
        });
    });


    $('body').on('click', 'table button.btn', function() {
        $(this).parents('tr').next().toggle();
    });


    var getRotate = function(url) {
        if (!url) {
            return 0;
        }
        var arr = url.split('/');
        for (var i = 0, len = arr.length; i < len; i++) {
            if (arr[i] === 'rotate') {
                return parseInt(arr[i + 1], 10);
            }
        }
        return 0;
    };

    $('#myModal-img .modal-body-footer').find('a').on('click', function() {
        var img = $('#myModal-img').find('.modal-body img');
        var key = img.data('key');
        var oldUrl = img.attr('src');
        var originHeight = parseInt(img.data('h'), 10);
        var fopArr = [];
        var rotate = getRotate(oldUrl);
        if (!$(this).hasClass('no-disable-click')) {
            $(this).addClass('disabled').siblings().removeClass('disabled');
            if ($(this).data('imagemogr') !== 'no-rotate') {
                fopArr.push({
                    'fop': 'imageMogr2',
                    'auto-orient': true,
                    'strip': true,
                    'rotate': rotate,
                    'format': 'png'
                });
            }
        } else {
            $(this).siblings().removeClass('disabled');
            var imageMogr = $(this).data('imagemogr');
            if (imageMogr === 'left') {
                rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
            } else if (imageMogr === 'right') {
                rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
            }
            fopArr.push({
                'fop': 'imageMogr2',
                'auto-orient': true,
                'strip': true,
                'rotate': rotate,
                'format': 'png'
            });
        }

        $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {

            var watermark = $(this).data('watermark');
            var imageView = $(this).data('imageview');
            var imageMogr = $(this).data('imagemogr');

            if (watermark) {
                fopArr.push({
                    fop: 'watermark',
                    mode: 1,
                    image: 'http://www.b1.qiniudn.com/images/logo-2.png',
                    dissolve: 100,
                    gravity: watermark,
                    dx: 100,
                    dy: 100
                });
            }

            if (imageView) {
                var height;
                switch (imageView) {
                    case 'large':
                        height = originHeight;
                        break;
                    case 'middle':
                        height = originHeight * 0.5;
                        break;
                    case 'small':
                        height = originHeight * 0.1;
                        break;
                    default:
                        height = originHeight;
                        break;
                }
                fopArr.push({
                    fop: 'imageView2',
                    mode: 3,
                    h: parseInt(height, 10),
                    q: 100,
                    format: 'png'
                });
            }

            if (imageMogr === 'no-rotate') {
                fopArr.push({
                    'fop': 'imageMogr2',
                    'auto-orient': true,
                    'strip': true,
                    'rotate': 0,
                    'format': 'png'
                });
            }
        });

        var newUrl = Qiniu.pipeline(fopArr, key);

        var newImg = new Image();
        img.attr('src', '/public/images/loading.gif');
        newImg.onload = function() {
            img.attr('src', newUrl);
            img.parent('a').attr('href', newUrl);
        };
        newImg.src = newUrl;
        return false;
    });

    $('.process_box').change(function () {
        if($(this).is(':checked')) {
            $(this).parents('.process').find('.process_show').show();
        } else {
            $(this).parents('.process').find('.process_show').hide();
        }
    });

    $('#startEnd').change(function () {
        if($(this).is(':checked')) {
            $('#if_cut').attr('checked', false).attr('disabled', true);
        } else {
            $('#if_cut').attr('disabled', false);
        }
    });

    $('#waterMark').change(function () {
        if($(this).is(':checked')) {
            $('#waterMarkType').attr('checked', false).attr('disabled', true);
        } else {
            $('#if_cut').attr('disabled', false);
        }
    });

    $('#isAsync').change(function () {
        if($(this).is(':checked')) {
            $('#if_cut').attr('checked', false).attr('disabled', true);
        } else {
            $('#if_cut').attr('disabled', false);
        }
    });


    $("#videoProcess").click(function () {
        var width = $('#videoWidth').val();
        var height = $('#videoHeight').val();
        var length = parseInt($('#videoLength').val());
        var intervalid = '';
        var key = $('#videoKey').val();
        var fetchStatus = function (persistentId) {
            var statusUrl = '/index.php?m=Admin&c=VideoSplice&a=status';
            var timeoutId = '';
            $.ajax({
                url:statusUrl + '&id=' + persistentId,
                dataType: 'json',
                success: function (result) {
                    if(result.status == 'success') {
                        console.log('new video:' + result.url);
                        $('#videoShow').attr('src', result.url);
                        $('#videoKey').val(result.key);
                        $("#loading_mask").css("display","none");
                        clearTimeout(timeoutId);
                        return '';
                    }
                    if(result.status == 'error') {
                        console.log('new video get error');
                        $("#loading_mask").css("display","none");
                        clearTimeout(timeoutId);
                        return '';
                    }
                },
                error: function (xhr, textStatus) {
                    console.log('status:' + xhr.status);
                    console.log('report:' + textStatus);
                    console.log('custom uptoken_func err');
                    $("#loading_mask").css("display","none");
                    clearTimeout(timeoutId);
                    return '';
                }
            });
            timeoutId = setTimeout(fetchStatus, 1800, persistentId);
        };
        var isAsync = false;
        var start, end, videoName, reqData= '';
        reqData = reqData+ 'key='+ key + '&width='+ width + '&height=' + height;
        if($('#waterMark').is(':checked')) {
            water_type = $('#water_type option:selected').val();
            reqData = reqData + '&is_water=' + 1 + '&water_type=' + water_type;
        } else {
            reqData = reqData + '&is_water=' + 0;
        }
        if($('#startEnd').is(':checked')) {
            videoName = $('#videoResult').val();
            reqData = reqData + '&is_start=' + 1 + '&video_name' + videoName;
        } else {
            reqData = reqData + '&is_start=' + 0;
        }
        if($("#if_cut").is(':checked')) {
            start = $('#video_cut_start').val()?parseInt($('#video_cut_start').val()) : 0;
            end = $('#video_cut_end').val()?parseInt($('#video_cut_end').val()) : length;
            if (start<0 || start > length || end > length || end < 0) {
                alert('截取时间段有无效！');
                return;
            }
            reqData = reqData + '&is_cut=' + 1 + '&cut_start=' + start + '&cut_end=' + end;
        }else {
            reqData = reqData + '&is_cut=' + 0;
        }
        if($("#isAsync").is(':checked')) {
            reqData = reqData + '&is_async=' + 1;
            isAsync = true;
        }else{
            reqData = reqData + '&is_async=' + 0;
        }
        var remoteUrl = '/index.php?m=Admin&c=VideoSplice&a=fops';
        $.ajax({
            url:remoteUrl + '&' + reqData,
            dataType: 'json',
            success: function (result) {
                if(isAsync) {
                    console.log('new video:' + result.url);
                    $('#videoShow').attr('src', result.url);
                    $('#videoKey').val(result.key);
                    $("#loading_mask").css("display","none");
                    return '';
                } else {
                    fetchStatus(result.id);
                }
            },
            error: function (xhr, textStatus) {
                console.log('status:' + xhr.status);
                console.log('report:' + textStatus);
                console.log('custom uptoken_func err');
                $("#loading_mask").css("display","none");
                return '';
            },
            beforeSend:function(){
                $("#loading_mask").css("display","block");
            }
        });

    });
}));
